package com.zz.yt.lib.ui.base;

import androidx.annotation.NonNull;

import com.blankj.utilcode.util.ConvertUtils;
import com.blankj.utilcode.util.EncryptUtils;
import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.ObjectUtils;
import com.java.lib.gm.GmUtils;
import com.whf.android.jar.app.Latte;
import com.whf.android.jar.base.latte.BaseProxyActivity;
import com.whf.android.jar.dao.TokenDao;
import com.whf.android.jar.dao.UserDao;
import com.whf.android.jar.net.HttpCode;
import com.whf.android.jar.net.RestClient;
import com.whf.android.jar.net.callback.ISuccess;
import com.whf.android.jar.net.utils.RestClientUtils;
import com.whf.android.jar.util.log.LatteLogger;
import com.zz.yt.lib.ui.aes.AesKeys;
import com.zz.yt.lib.ui.entity.LoginEntry;
import com.zz.yt.lib.ui.listener.OnClickStringListener;
import com.zz.yt.lib.ui.utils.ObjUtils;

import java.util.Map;
import java.util.WeakHashMap;

/***
 * 主界面
 * @author qf
 * @version 1.0
 * @version 2020-03-23
 */
public abstract class BaseExampleActivity extends BaseProxyActivity {

    /**
     * 参数
     */
    private final static String TAG = "参数";

    /**
     * 默认登录的token
     */
    protected final static String SIGN_TOKEN = "Basic cGlnOnBpZw==";

    /**
     * @param password:需加密的密码
     */
    protected String getPassAes(String password) {
        return getPassAes(password, AesKeys.KEY_AES);
    }

    /**
     * @param password:需加密的密码
     * @param strKey：密钥       (需要前端和后端保持一致)
     */
    protected String getPassAes(String password, String strKey) {
        return getPassAes(password, strKey, AesKeys.AES_CBC_PK_CS5_PADDING);
    }

    /**
     * @param password:需加密的密码
     * @param strKey：密钥       (需要前端和后端保持一致)
     * @param aes：算法
     */
    protected String getPassAes(String password, String strKey, String aes) {
        final byte[] bytesDataAes = ConvertUtils.string2Bytes(password);
        final byte[] bytesKeyAes = ConvertUtils.string2Bytes(strKey);
        return ConvertUtils.bytes2String(EncryptUtils.encryptAES2Base64(bytesDataAes,
                bytesKeyAes, aes, bytesKeyAes));
    }

    /**
     * @param url:登录接口(post)
     * @param params:登录参数
     */
    protected void loginStart(String url, WeakHashMap<String, Object> params) {
        RestClientUtils.create(this, this).inPost(url, params, new ISuccess() {
            @Override
            public void onSuccess(String response) {
                onLoginSuccess(response);
            }
        });
    }

    /**
     * @param url:登录接口(post)
     * @param params:登录参数(直接拼接)
     */
    protected void loginPost(String url, WeakHashMap<String, Object> params) {
        LatteLogger.json(TAG, GsonUtils.toJson(params));
        showLoading();
        RestClient.builder()
                .url(url)
                .params(params)
                .analysis(true)
                .success(new ISuccess() {
                    @Override
                    public void onSuccess(String response) {
                        onLoginSuccess(response);
                    }
                })
                .failure(this)
                .error(this)
                .build()
                .post();
    }

    /**
     * @param url:登录接口(post)
     * @param params:登录参数
     */
    @Deprecated
    protected void startLogin(String url, WeakHashMap<String, Object> params) {
        loginStart(url, params);
    }


    /**
     * @param url:登录接口(post)
     * @param params:登录参数(国密)
     */
    protected void loginStartGm(String url, WeakHashMap<String, Object> params) {
        LatteLogger.json(TAG, GsonUtils.toJson(params));
        Map<String, String> gmMap = GmUtils.getGmSm(GsonUtils.toJson(params));
        LatteLogger.json("国密", GsonUtils.toJson(gmMap));
        showLoading();
        RestClient.builder()
                .url(url)
                .headers("SecureTransport", true)
                .raw(GsonUtils.toJson(gmMap))
                .analysis(true)
                .success(new ISuccess() {
                    @Override
                    public void onSuccess(String response) {
                        onLoginSuccess(response);
                    }
                })
                .failure(this)
                .error(this)
                .build()
                .post();
    }


    /**
     * @param url:登录接口(query)
     * @param params:登录参数
     */
    protected void loginQuery(String url, WeakHashMap<String, Object> params) {
        LatteLogger.json(TAG, GsonUtils.toJson(params));
        showLoading();
        RestClient.builder()
                .url(url)
                .params(params)
                .analysis(true)
                .success(new ISuccess() {
                    @Override
                    public void onSuccess(String response) {
                        onLoginSuccess(response);
                    }
                })
                .failure(this)
                .error(this)
                .build()
                .query();
    }

    /**
     * @param url:登录接口(query)
     * @param params:登录参数
     */
    @Deprecated
    protected void queryLogin(String url, WeakHashMap<String, Object> params) {
        loginQuery(url, params);
    }

    /**
     * @param response:默认返回处理
     * @param listener：返回的data
     */
    @Deprecated
    protected void code(String response, OnClickStringListener listener) {
        hideLoading();
        if (ObjectUtils.isEmpty(response) || listener == null) {
            return;
        }
        final int code = ObjUtils.getCode(response);
        if (HttpCode.CODE_200 == code) {
            final String data = ObjUtils.getData(response);
            listener.onClick(data);
        } else {
            onError(code, Latte.getMessage(response));
        }
    }

    protected void onLoginSuccess(String response) {
        final LoginEntry loginEntry = GsonUtils.fromJson(response, LoginEntry.class);
        setLoginData(loginEntry);
    }

    /**
     * @param str：登录用户信息
     */
    protected void setLoginData(@NonNull LoginEntry str) {
        //header格式为 Authorization:Bearer {access_token}
        TokenDao.setAuthorization(str.getToken_type() + " " + str.getAccess_token());
        UserDao.setUserId(str.getUserId());
        UserDao.setUserName(str.getUsername());
        //登录成功
    }

    @Override
    public void onError(int code, String msg) {
        super.onError(code, ObjectUtils.isEmpty(msg) ? "登录失败，请稍后再试。" : msg);
    }
}
